﻿#region itdc

/************************************************************************
*Copyright(C) 2015 by qsgy
 *All rights reserved. 
 *FileName:     $safeitemname$
 *Author:       oyh
 *Version:      
 *UnityVersion：
 *Date:   $time$      
 *Description:    
 *History: 
************************************************************************/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 巡逻状态(Monster使用的版本)
/// </summary>
[RequireComponent(typeof(Mover))]
public class PatrolState : FSMState
{
    #region field
    [SerializeField, Tooltip("绑定的移动者脚本")]
    private Mover mover;
    [Tooltip("巡逻目标点")]
    public Vector3[] tagerts=new Vector3[] { };
    [SerializeField, Tooltip("寻路路径点索引")]
    private int index = 0;
    [SerializeField, Tooltip("判定到达目标点的接触距离")]
    public float reach = 0.5f;
    #endregion
    public PatrolState() {
        id = StateID.Patrol;

    }
    #region mono


   
    private void Awake()
    {
        id = StateID.Patrol;
        mover = GetComponent<Mover>();
#if DEBUG
        if (mover == null)
        {
            Debug.LogError("巡逻状态没有找到怪物脚本");

        }
        if (tagerts.Length == 0)
        {
            Debug.LogError("巡逻状态目标位置为空");
            return;
        }
#endif

    }
    private void Start()
    {
        mover.tagertPos = tagerts[index];//设置第一个目标点
        
    }


    private void OnDrawGizmos()
    {
        int leng = tagerts.Length;
        if (leng < 2) return;
        for (int i = 0; i < leng-1; i++)
        {

            Gizmos.DrawLine(tagerts[i], tagerts[i + 1]);
        }

        Gizmos.DrawLine(tagerts[0], tagerts[leng-1]);
     
    }
  
    public override void CheckFresh()
    {
        if (Arrived()) NextIndex();//如果到达目标点，则目标设置为下一个点
    }
    #endregion





    #region Judge methods

    /// <summary>
    /// 是否到达当前目标位置
    /// </summary>
    /// <returns></returns>
    private bool Arrived()
    {
        if ((tagerts[index] - mover.selfTransform.position).magnitude <= reach) return true;
        return false;
    }

    /// <summary>
    /// 切换到下一个目标点
    /// </summary>
    private void NextIndex()
    {
        index++;
        if (index >= tagerts.Length) index = 0;
        mover.tagertPos = tagerts[index];//设置新的目标点
    } 
    #endregion
}
